﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gpsys.Entity.MSG;
using Gpsys.Logger;

namespace Gpsys.Web.Business
{
    /// <summary>
    /// ServerBusiness
    /// </summary>
    public class ServerBusiness : BaseBusiness
    {
        /// <summary>
        /// Pings to database.
        /// </summary>
        /// <param name="serverId">The server id.</param>
        public void PingToDatabase(int serverId)
        {
            try
            {
                SQL.OpenConnection();

                SQL.Execute(@"Update Server
                                Set [LastPingActivity] = getdate()
                                Where Id = @Id", new { Id = serverId });

            }
            catch (Exception ex)
            {

            }
            finally
            {
                SQL.CloseConnection();
            }
        }

        /// <summary>
        /// Checks the server registered.
        /// </summary>
        /// <param name="serverId">The server id.</param>
        /// <returns></returns>
        public bool CheckServerRegistered(int serverId)
        {
            try
            {
                SQL.OpenConnection();

                var id = SQL.Query<int>("Select Id from Server Where Id = @Id", new { Id = serverId }).SingleOrDefault();

                return id == serverId;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
                SQL.CloseConnection();
            }
        }

        public List<Server> GetServers()
        {
            try
            {
                SQL.OpenConnection();

                return SQL.Query<Server>(@"SELECT [Id]
                                          ,[Code]
                                          ,[Name]
                                          ,[Description]
                                          ,[LastPingActivity]
                                         FROM [Server]").ToList();

            }
            catch (Exception e)
            {
                Log.WriteError("GetServers : " + e.Message);

                return new List<Server>();
            }
            finally
            {
                SQL.CloseConnection();
            }
        }
    }
}
